﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AutoHistory.Core;
using System.Globalization;

namespace AutoHistory2010ForWord
{
    public partial class HistoryTaskPane : UserControl
    {
        private Microsoft.Office.Interop.Word.Application application;
        private string sourceFile;

        public HistoryTaskPane(Microsoft.Office.Interop.Word.Application application)
        {
            this.application = application;
            InitializeComponent();
        }

        #region Public Methods

        public void UpdateHistory()
        {
            labelError.Visible = false;

            listViewHistory.Items.Clear();

            if (String.IsNullOrEmpty(this.sourceFile))
                return;

            try
            {
                foreach (HistoryFile item in HistoryManager.GetHistoryList(sourceFile))
                {
                    ListViewItem li = new ListViewItem(item.Date.ToString("yyyy/MM/dd - HH:mm:ss", CultureInfo.InvariantCulture));
                    li.Tag = item.Timestamp;
                    listViewHistory.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                //SetStatus("An error occured loading the history:" + Environment.NewLine + ex.Message);
                SetStatus(Resource.ErrorLoadingHistory + Environment.NewLine + ex.Message);
            }
        }

        public void SetSourceFile(string sourceFile)
        {
            this.sourceFile = sourceFile;
        }

        public void SetStatus(string message)
        {
            labelError.Text = message;
            labelError.Visible = true;
        }

        #endregion

        #region Private Methods

        private long GetSelectedTimeStamp()
        {
            return (long)listViewHistory.SelectedItems[0].Tag;
        }

        private long[] GetSelectedTimeStamps()
        {
            List<long> ts = new List<long>();
            foreach (ListViewItem item in listViewHistory.SelectedItems)
            {
                ts.Add((long)item.Tag);
            }
            return ts.ToArray();
        }

        private void ViewSelectedFile()
        {
            labelError.Visible = false;

            if (listViewHistory.SelectedItems.Count == 0)
                return;

            try
            {
                long timestamp = GetSelectedTimeStamp();
                HistoryManager.OpenFile(this.sourceFile, timestamp);
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message);
            }
        }

        #endregion

        #region Event Handler

        private void listViewHistory_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            buttonRecover.Enabled = (listViewHistory.SelectedItems.Count == 1);
            buttonView.Enabled = (listViewHistory.SelectedItems.Count == 1);
            buttonDelete.Enabled = (listViewHistory.SelectedItems.Count > 0);
            buttonCompare.Enabled = (listViewHistory.SelectedItems.Count == 1);
        }

        private void listViewHistory_DoubleClick(object sender, EventArgs e)
        {
            ViewSelectedFile();
        }

        private void buttonView_Click(object sender, EventArgs e)
        {
            ViewSelectedFile();
        }

        private void buttonRecover_Click(object sender, EventArgs e)
        {
            labelError.Visible = false;

            if (listViewHistory.SelectedItems.Count == 0)
                return;

            //DialogResult dr = MessageBox.Show("This will override the current file with the selected version." + Environment.NewLine + "Are you sure?", "AutoHistory", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            DialogResult dr = MessageBox.Show(Resource.RecoverFile, "AutoHistory", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dr != DialogResult.Yes)
                return;

            try
            {
                // close the current document
                object a1 = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
                object a2 = Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat;
                object a3 = false;
                ((Microsoft.Office.Interop.Word._Document)this.application.ActiveDocument).Close(ref a1, ref a2, ref a3);

                long timestamp = GetSelectedTimeStamp();
                HistoryManager.RecoverFile(this.sourceFile, timestamp);

                // open the document again
                object f = false;
                object t = true;
                object es = String.Empty;
                object frm = Microsoft.Office.Interop.Word.WdOpenFormat.wdOpenFormatAuto;
                object me = Microsoft.Office.Core.MsoEncoding.msoEncodingAutoDetect;
                object wd = Microsoft.Office.Interop.Word.WdDocumentDirection.wdLeftToRight;
                object file = this.sourceFile;
                this.application.Documents.Open(ref file, ref f, ref f, ref t, ref es, ref es, ref f, ref es, ref es, ref frm, ref me, ref t, ref f, ref wd, ref f, ref es);

                UpdateHistory();
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message);
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            labelError.Visible = false;

            if (listViewHistory.SelectedItems.Count == 0)
                return;

            try
            {
                long[] timestamps = GetSelectedTimeStamps();
                HistoryManager.DeleteFiles(this.sourceFile, timestamps);

                UpdateHistory();
            }
            catch (Exception ex)
            {
                SetStatus(ex.Message);
            }
        }

        #endregion

        private void AutoHistoryForm_Enter(object sender, EventArgs e)
        {
            this.UpdateHistory();
        }

        private void buttonCompare_Click(object sender, EventArgs e)
        {
            long timestamp = GetSelectedTimeStamp();

            string newFile = string.Empty;

            newFile = HistoryManager.GetFilename(this.sourceFile, timestamp);

            WordComparer cmp = new WordComparer(this.application);
            cmp.Compare(this.sourceFile, newFile);
        }
    }
}
